package org.groovyflow.spring.web.prettyURL;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.groovyflow.spring.web.*;
import org.groovyflow.interceptor.*;

public class PrettyURLDynamicFinder extends AbstractDynamicFinder {
	private InterceptorHandler beforeHandler;
	private InterceptorHandler afterHandler;
	private InterceptorCache interceptorCache;
	
	/**
	 * A url of http://yourServer;yourPort/yourWebAppName/controllerX/methodNameY will
	 * cause controllerX's methodNameY to be invoked.  If we only see 
	 * controllerX with no following methodName, we'll check the http method, convert it
	 * to lowercase, and invoke the like-named method on controlerX. 
	 */
	protected List findObjectAndMethod(HttpServletRequest request, 
			HttpServletResponse response, 
			ClassLoader classLoader){
		String ctrlString = findControlString(request);
		if(ctrlString.startsWith("/"))
			ctrlString = ctrlString.substring(1);
		StringTokenizer tk = new StringTokenizer(ctrlString, "/");
		List tokens = new ArrayList();
		while(tk.hasMoreTokens()){
			tokens.add(tk.nextToken());
		}
		if(tokens.isEmpty())
			throw new RuntimeException("Can't find class/method(or block) for " + ctrlString);
		String className = putClassNameTogether((String) tokens.get(0));
		Class clazz  = findClass(className, classLoader);
		Object theController = instantiate(clazz);
		//TODO  ??Make some allowance for the second element of the String being 
		//all digits, in which case we'll treat it as an id??  I've always thought that idea is stupid.
		String methName = tokens.size() == 1 ? request.getMethod().toLowerCase() : (String) tokens.get(1);
		Method method = findMethod(clazz, methName);
		
		List objAndMeth = new ArrayList();
		objAndMeth.add(theController);
		objAndMeth.add(method);
		
		return objAndMeth;

	}
	
	public boolean isPrettyURLScheme() {
		return true;
	}	
	
	
}
